import { useCreation } from 'ahooks';
import React, { useCallback, useMemo } from 'react';
import { useContextSelector } from 'use-context-selector';

import PromptEditor from '@/components/Textarea/PromptEditor';
import { t } from '@/locales/i18n';
import { AppContext } from '@/pages/app/detail/context';

import { WorkflowContext } from '../../../../../context';
import { getEditorVariables } from '../../../../../utils';

import type { RenderInputProps } from '../type';

const TextareaRender = ({
  inputs = [],
  item,
  nodeId,
  isDisabled = false,
}: RenderInputProps & { isDisabled?: boolean }) => {
  const nodeList = useContextSelector(WorkflowContext, (v) => v.nodeList);
  const edges = useContextSelector(WorkflowContext, (v) => v.edges);
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);

  const { appDetail } = useContextSelector(AppContext, (v) => v);

  // get variable
  const variables = useCreation(() => {
    return getEditorVariables({
      nodeId,
      nodeList,
      edges,
      appDetail,
      t,
    });
  }, [nodeId, nodeList, edges, appDetail, t]);

  const onChange = useCallback(
    (e: string) => {
      onChangeNode({
        nodeId,
        type: 'updateInput',
        key: item.key,
        value: {
          ...item,
          value: e,
        },
      });
    },
    [item, nodeId, onChangeNode],
  );

  const Render = useMemo(() => {
    return (
      <PromptEditor
        variableLabels={variables}
        variables={variables}
        title={t(item.label as any)}
        maxLength={item.maxLength}
        minH={100}
        maxH={300}
        placeholder={t((item.placeholder as any) || '')}
        value={item.value}
        onChange={onChange}
        showOpenModal={!isDisabled}
      />
    );
  }, [isDisabled, item.label, item.maxLength, item.placeholder, item.value, onChange, variables]);

  return Render;
};

export default React.memo(TextareaRender);
